package com.hzchendou.blog.demo.example;

import com.hzchendou.blog.demo.entity.BlogDO;
import com.hzchendou.blog.demo.mapper.BlogMapper;
import com.hzchendou.blog.demo.params.PageVO;
import java.io.IOException;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSession;

/**
 * 案例四- 分页插件
 *
 * @Date: 2022-07-08 15:11
 * @since: 1.0
 */
@Slf4j
public class Case4 extends AbstractCase {

    @Override
    public void run() throws IOException {
        /// 使用Java 7提供的 try-with-resource写法，让JVM自动完成资源关闭操作
        try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
            //// 获取Mapper接口示例（底层使用了JDK的Proxy.newProxyInstance方法创建代理）
            BlogMapper blogMapper = sqlSession.getMapper(BlogMapper.class);
            PageVO<BlogDO> result = selectPage(blogMapper, 1, 2);
            log.info("分页查询博客文章列表信息, {}", result);
        }
    }


    private PageVO<BlogDO> selectPage(BlogMapper blogMapper, int page, int size) {
        PageVO<BlogDO> param = new PageVO();
        param.setPage(page);
        param.setSize(size);
        List<BlogDO> blogs = blogMapper.selectPage(param);
        param.setRecords(blogs);
        param.setPageSize(blogs == null ? 0 : blogs.size());
        return param;
    }
}
